package com.ruoyi.clf.service.impl;
import com.ruoyi.clf.domain.MerchantAggregationResult;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class EvaluateService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


   public List<MerchantAggregationResult> testMerchantAggregation() throws Exception {
        // 构建搜索请求（替换 "evaluate" 为实际索引名）
        SearchRequest searchRequest = new SearchRequest("evaluate");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(0); // 不返回文档

        // 添加聚合：按 merchant_id 分组，内部计算 rate 平均值
        searchSourceBuilder.aggregation(
                AggregationBuilders.terms("group_by_merchant")
                        .field("merchant_id")
                        .order(BucketOrder.key(true)) // 按 _key（merchant_id）升序
                        .subAggregation(AggregationBuilders.avg("avg_rate").field("rate"))
        );

        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 解析聚合结果
        List<MerchantAggregationResult> resultList = new ArrayList<>();
        Terms groupByMerchant = searchResponse.getAggregations().get("group_by_merchant");
        for (Terms.Bucket bucket : groupByMerchant.getBuckets()) {
            long merchantId = (long) bucket.getKey(); // 商户 ID
            long docCount = bucket.getDocCount(); // 文档数
            Avg avgRate = bucket.getAggregations().get("avg_rate"); // 平均评分聚合
            double rateValue = avgRate.getValue(); // 平均评分值

//            把数据放到list中
            MerchantAggregationResult result = new MerchantAggregationResult();
            result.setKey(merchantId);
            result.setDocCount(docCount);
            result.setAvgRate(rateValue);
            resultList.add(result);
//            System.out.println("商户 ID: " + merchantId);
//            System.out.println("文档数: " + docCount);
//            System.out.println("平均评分: " + rateValue);
//            System.out.println("------------------------------");
        }
        return resultList;
    }
}